﻿using System;
using System.IO;
using UnityEngine;
using Application = UnityEngine.Device.Application;

namespace GameFramework.data
{
    public class LocalLoadSaveStrategy:LoadSaveStrategy
    {
        public string dataPath = Application.persistentDataPath + "datas/";
        public T load<T>() where T:class,IData,new()
        {
            string filePath = dataPath + typeof(T).Name;
            if (!File.Exists(filePath))
            {
                return null;
            }

            try
            {
                T fromJson = JsonUtility.FromJson<T>(filePath);
                return fromJson;
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }

            return null;
        }

        public void save(IData data)
        {
            if (data == null)
            {
                return;
            }
            string filePath = dataPath + data.GetType().Name;
            if (!File.Exists(filePath))
            {
                File.Create(filePath);
            }

            string json = JsonUtility.ToJson(data);
            File.WriteAllText(filePath,json);
        }
    }
}